using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Data;

namespace Pixysoft.Data
{
    public class DataGridViewMapping
    {
        private static DataGridViewMapping instance;
        public static DataGridViewMapping Instance
        {
            get
            {
                lock (typeof(DataGridViewMapping))
                {
                    if (instance == null)
                        instance = new DataGridViewMapping();
                    return instance;
                }
            }
        }

        public void MappingOneToOne(DataGridViewRow fromRow, DataRow toRow)
        {
            if (fromRow == null)
                throw new Exception("Missing input parameter!");

            if (toRow == null)
                throw new Exception("Missing input parameter!");

            DataGridView fromTable = fromRow.DataGridView;
            if (fromTable.Columns.Count == 0)
                throw new Exception("Missing Column!");

            DataTable toTable = toRow.Table;
            if (toTable.Columns.Count == 0)
                throw new Exception("Missing Columns!");

            foreach (DataGridViewColumn fromColumn in fromTable.Columns)
            {
                string fromName = fromColumn.Name;
                string toName = fromColumn.Name;
                if (toName == null)
                    continue;
                if (!toTable.Columns.Contains(toName))
                    continue;

                if (fromRow.Cells[fromName].Value == null)
                    toRow[toName] = DBNull.Value;
                else
                    toRow[toName] = fromRow.Cells[fromName].Value;
            }
        }

        public void MappingOneToOne(DataRow fromRow, DataGridViewRow toRow)
        {
            if (fromRow == null)
                throw new Exception("Missing input parameter!");

            if (toRow == null)
                throw new Exception("Missing input parameter!");

            DataTable fromTable = fromRow.Table;
            if (fromTable.Columns.Count == 0)
                throw new Exception("Missing Column!");

            DataGridView toTable = toRow.DataGridView;
            if (toTable.Columns.Count == 0)
                throw new Exception("Missing Columns!");

            foreach (DataColumn fromColumn in fromTable.Columns)
            {
                string fromName = fromColumn.ColumnName;
                string toName = fromColumn.ColumnName;
                if (toName == null)
                    continue;
                if (!toTable.Columns.Contains(toName))
                    continue;

                toRow.Cells[fromName].Value = fromRow[fromName];
            }
        }
    }
}
